package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.domain.Market;
import com.chen.domain.TradeArea;
import com.chen.domain.UserFavoriteMarket;
import com.chen.dto.CoinDto;
import com.chen.fegin.CoinFegin;
import com.chen.mapper.TradeAreaMapper;
import com.chen.service.MarketService;
import com.chen.service.TradeAreaService;
import com.chen.service.UserFavoriteMarketService;
import com.chen.vo.MergeDeptVo;
import com.chen.vo.TradeAreaMarketVo;
import com.chen.vo.TradeMarketVo;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TradeAreaServiceImpl extends ServiceImpl<TradeAreaMapper, TradeArea> implements TradeAreaService{

    @Autowired
    private MarketService marketService;

    @Autowired
    private UserFavoriteMarketService userFavoriteMarketService;

    @Resource
    private CoinFegin coinFegin;

    @Override
    public List<TradeAreaMarketVo> getMarkets(Long userId) {
        List<UserFavoriteMarket> userFavoriteMarkets  = null;
        List<Long> marketIds = null;
        if(userId != null){
            userFavoriteMarkets = userFavoriteMarketService.list(new LambdaQueryWrapper<UserFavoriteMarket>()
                    .eq(UserFavoriteMarket::getUserId, userId));
            if(!CollectionUtils.isEmpty(userFavoriteMarkets)){
               marketIds = userFavoriteMarkets.stream().map(UserFavoriteMarket::getMarketId).collect(Collectors.toList());
            }
        }

        List<TradeAreaMarketVo> list = new ArrayList<>();

        List<TradeArea> tradeAreas = list(new LambdaQueryWrapper<TradeArea>()
                .eq(TradeArea::getStatus, 1));
        for(TradeArea tradeArea : tradeAreas){
            TradeAreaMarketVo tradeAreaMarketVo = new TradeAreaMarketVo();
            tradeAreaMarketVo.setAreaName(tradeArea.getName());
            //查询交易区域下包含的市场

            List<Market> markets = marketService.list(new LambdaQueryWrapper<Market>()
                    .eq(Market::getTradeAreaId, tradeArea.getId())
            .in(!CollectionUtils.isEmpty(marketIds),Market::getId,marketIds));

            if(CollectionUtils.isEmpty(markets)){
                continue;
            }

            List<TradeMarketVo> tradeAreaMarketVos = Lists.transform(markets, new Function<Market, TradeMarketVo>() {
                @NullableDecl
                @Override
                public TradeMarketVo apply(@NullableDecl Market market) {
                    TradeMarketVo areaMarketVo = new TradeMarketVo();
                    BeanUtils.copyProperties(market,areaMarketVo);
                    areaMarketVo.setPriceScale(market.getPriceScale());
                    areaMarketVo.setNumScale(market.getNumScale());

//                    /**
//                     * 当前价
//                     */
//                    @ApiModelProperty(value = "当前价")
//                    private BigDecimal price;
                    areaMarketVo.setPrice(market.getOpenPrice());
//
//                    /**
//                     * 价格单位
//                     */
//                    @ApiModelProperty(value = "价格单位")
//                    private String priceUnit;
                    Map<Long, CoinDto> coinByIds = coinFegin.getCoinByIds(Arrays.asList(market.getBuyCoinId()));
                    areaMarketVo.setPriceUnit(coinByIds.get(market.getBuyCoinId()).getName());
//
//                    /**
//                     * 当前价（人民币）
//                     */
//                    @ApiModelProperty(value = "当前价（人民币）")
//                    private BigDecimal cnyPrice;
//
//                    /**
//                     * 报价货币人民币价格
//                     */
//                    @ApiModelProperty(value = "报价货币人民币价格")
//                    private BigDecimal coinCnyPrice;
//
//                    /**
//                     * 合并深度
//                     */
//                    @ApiModelProperty(value = "合并深度")
//                    private List<MergeDeptVo> mergeDepth;
                    List<MergeDeptVo> mergeDepth = new ArrayList<>();

                    String depth = market.getMergeDepth();
                    //6  5  4   -- >  4  5  6
                    List<String> depthList = Arrays.asList(depth.split(","));
                    Collections.sort(depthList);

                    MergeDeptVo mergeDeptVoLow = new MergeDeptVo();
                    mergeDeptVoLow.setMergeType("LOW");
                    int i = Integer.parseInt(depthList.get(0));
                    BigDecimal deptVoLow  = BigDecimal.ONE.divide(new BigDecimal(Math.pow(10, i)));
                    mergeDeptVoLow.setValue(deptVoLow);
                    MergeDeptVo mergeDeptVoDef = new MergeDeptVo();
                    int o = Integer.parseInt(depthList.get(1));
                    BigDecimal deptVoDef = BigDecimal.ONE.divide(new BigDecimal(Math.pow(10, o)));

                    mergeDeptVoDef.setMergeType("DEF");
                    mergeDeptVoDef.setValue(deptVoDef);
                    MergeDeptVo mergeDeptVoHig = new MergeDeptVo();
                    int p = Integer.parseInt(depthList.get(2));
                    BigDecimal deptVoHig = BigDecimal.ONE.divide(new BigDecimal(Math.pow(10, p)));

                    mergeDeptVoHig.setMergeType("HIG");
                    mergeDeptVoHig.setValue(deptVoHig);

                    mergeDepth.add(mergeDeptVoLow);
                    mergeDepth.add(mergeDeptVoDef);
                    mergeDepth.add(mergeDeptVoHig);

                    areaMarketVo.setMergeDepth(mergeDepth);

//
//                    /**
//                     * 最高价
//                     */
//                    @ApiModelProperty(value = "最高价")
//                    private BigDecimal high;
                    areaMarketVo.setHigh(market.getOpenPrice());
//
//                    /**
//                     * 最低价
//                     */
//                    @ApiModelProperty(value = "最低价")
//                    private BigDecimal low;
                    areaMarketVo.setLow(market.getOpenPrice());
//
//                    /**
//                     * 日总交易量
//                     */
//                    @ApiModelProperty(value = "日总交易量")
//                    private BigDecimal volume = BigDecimal.ZERO;
//
//                    /**
//                     * 日总成交额
//                     */
//                    @ApiModelProperty(value = "日总成交额")
//                    private BigDecimal amount = BigDecimal.ZERO;
//
//                    /**
//                     * 涨幅
//                     */
//                    @ApiModelProperty(value = "涨幅")
//                    private double change;
                    areaMarketVo.setChange(0);

                    return areaMarketVo;
                }
            });
            tradeAreaMarketVo.setMarkets(tradeAreaMarketVos);
            list.add(tradeAreaMarketVo);
        }
        return list;
    }
}
